///////////////////////////////////////////////////////////////////////////////
///
/// GoogleDataSettings.cs
/// 
/// (c)2013 Kim, Hyoun Woo
///
///////////////////////////////////////////////////////////////////////////////
using UnityEngine;
using UnityEditor;
using System.Collections;
using System.IO;
using System.Collections.Generic;

namespace UnityQuickSheet
{
    /// <summary>
    /// A class manages google account setting.
    /// </summary>
    public class GoogleDataSettings : ScriptableObject
    {
        public static string AssetPath = "Assets/QuickSheet/GDataPlugin/Editor/";

        public static readonly string AssetFileName = "GoogleDataSettings.asset";

        // A flag which indicates use local installed oauth2 json file for authentication or not.
        static public bool useOAuth2JsonFile = false;

        public string JsonFilePath
        {
            get { return jsonFilePath; }
            set
            {
                if (string.IsNullOrEmpty(value) == false)
                    jsonFilePath = value;
            }
        }
        private string jsonFilePath = string.Empty;

        /// <summary>
        /// A path where generated ScriptableObject derived class and its data class script files are to be put.
        /// </summary>
        public string RuntimePath = string.Empty;

        /// <summary>
        /// A path where generated editor script files are to be put.
        /// </summary>
        public string EditorPath = string.Empty;

        [System.Serializable]
        public struct OAuth2JsonData
        {
            public string client_id;
            public string auth_uri;
            public string token_uri;
            public string auth_provider_x509_cert_url;
            public string client_secret;
            public List<string> redirect_uris;
        };

        public OAuth2JsonData OAuth2Data;

        // enter Access Code after getting it from auth url
        public string _AccessCode = "Paste AcecessCode here!";

        // enter Auth 2.0 Refresh Token and AccessToken after succesfully authorizing with Access Code
        public string _RefreshToken = "";

        public string _AccessToken = "";

        /// <summary>
        /// A singleton instance.
        /// </summary>
        private static GoogleDataSettings s_Instance;

        /// <summary>
        /// Create new account setting asset file if there is already one then select it.
        /// </summary>
        [MenuItem("Assets/Create/QuickSheet/Setting/GoogleData Setting")]
        public static void CreateGoogleDataSetting()
        {
            GoogleDataSettings.Create();
        }

        /// <summary>
        /// Select currently exist account setting asset file.
        /// </summary>
        [MenuItem("Edit/Project Settings/QuickSheet/Select Google Data Setting")]
        public static void Edit()
        {
            Selection.activeObject = Instance;
            if (Selection.activeObject == null)
            {
                Debug.LogError("No GoogleDataSettings.asset file is found. Create setting file first.");
            }
        }

        /// <summary>
        /// Checks GoogleDataSetting.asset file exist at the specified path(AssetPath+AssetFileName).
        /// </summary>
        public bool CheckPath()
        {
            string file = AssetDatabase.GetAssetPath(Selection.activeObject);
            string assetFile = AssetPath + GoogleDataSettings.AssetFileName;

            return (file == assetFile) ? true : false;
        }

        /// <summary>
        /// A property for a singleton instance.
        /// </summary>
        public static GoogleDataSettings Instance
        {
            get
            {
                if (s_Instance == null)
                {
                    string path = GoogleDataSettings.AssetPath + GoogleDataSettings.AssetFileName;
                    s_Instance = (GoogleDataSettings)AssetDatabase.LoadAssetAtPath(path, typeof(GoogleDataSettings));
                    if (s_Instance == null)
                    {
                        string title = string.Format(@"No {0} is found!", AssetFileName);
                        string message = string.Format(@"No {0} is found at '{1}'. \n Press 'Create' button to create a default one.", AssetFileName, AssetPath);
                        bool ok = EditorUtility.DisplayDialog(
                            title,
                            message,
                            "Create",
                            "Cancel"
                        );

                        if (ok)
                            s_Instance = GoogleDataSettings.Create();
                    }
                }
                return s_Instance;
            }
        }

        /// <summary>
        /// Create .asset file for google spreadsheet setting if it does not exist.
        /// </summary>
        public static GoogleDataSettings Create()
        {
            string filePath = CustomAssetUtility.GetUniqueAssetPathNameOrFallback(AssetFileName);
            s_Instance = (GoogleDataSettings)AssetDatabase.LoadAssetAtPath(filePath, typeof(GoogleDataSettings));

            if (s_Instance == null)
            {
                s_Instance = CreateInstance<GoogleDataSettings>();

                string path = CustomAssetUtility.GetUniqueAssetPathNameOrFallback(AssetFileName);
                AssetDatabase.CreateAsset(s_Instance, path);

                GoogleDataSettings.AssetPath = Path.GetDirectoryName(path);
                GoogleDataSettings.AssetPath += "/";

                // saves file path of the created asset.
                EditorUtility.SetDirty(s_Instance);
                AssetDatabase.SaveAssets();

                EditorUtility.DisplayDialog(
                    "Validate Settings",
                    "Default google data settings file has been created for accessing Google project page. You should validate these before proceeding.",
                    "OK"
                );
            }
            else
            {
                Debug.LogWarning("Already exist at " + filePath);
            }

            Selection.activeObject = s_Instance;

            return s_Instance;
        }
    }
}